package com.autonavi.yunda.yunji.core.service.dbfactory;

import com.autonavi.yunda.yunji.common.exception.AmapPreconditions;
import com.autonavi.yunda.yunji.common.thread.TraceableThreadPoolTaskExecutor;
import com.autonavi.yunda.yunji.common.utils.JsonUtils;
import com.autonavi.yunda.yunji.core.enums.DBType;
import com.autonavi.yunda.yunji.core.enums.DatasourceType;
import com.autonavi.yunda.yunji.core.service.dbhelper.TairHelper;
import com.autonavi.yunda.yunji.core.vo.datasource.config.TairDataConfig;
import com.taobao.tair.impl.mc.MultiClusterTairManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

/**
 * redis工厂
 */
@Repository
@Slf4j
public class TairFactoryService extends AbstractDataSourceFactory<TairHelper> {

    @Autowired
    TraceableThreadPoolTaskExecutor tairAsyncExecutor;

    @Override
    public DBType getDbType() {
        return DBType.TAIR;
    }

    /**
     * 生成数据源，并放入容器中
     */
    @Override
    public TairHelper createDataSource(DatasourceType dataSourceType, String dataSourceConfig) {
        TairDataConfig config = JsonUtils.from(dataSourceConfig, TairDataConfig.class);
        String userName = config.username;
        Integer namespace = config.namespace;
        Integer timeout = config.timeout;
        AmapPreconditions.checkArgument(StringUtils.hasLength(userName));
        AmapPreconditions.checkArgument(namespace != null);
        AmapPreconditions.checkArgument(timeout != null);
        log.info("TairHelper:" + userName + ";" + namespace);
        MultiClusterTairManager tairManager = new MultiClusterTairManager();
        tairManager.setUserName(userName);
        tairManager.setDynamicConfig(config.dynamic);
        // 向服务端注册热点key反馈功能
        tairManager.setNeedRegisterClientVersion(true);
        tairManager.setTimeout(timeout);
        //连接自己的单元机房，如果刷缓存需要双刷
        tairManager.setUnit("center");
        tairManager.init();
        return new TairHelper(namespace, tairManager, tairAsyncExecutor);
    }

    @Override
    public void close(TairHelper dataSource) {
        if (dataSource == null) {
            return;
        }
        dataSource.close();
    }
}
